﻿using System;
using System.Collections.Generic;

namespace NetTopologySuite.Triangulate.QuadEdge
{
	public class EdgeConnectedTriangleTraversal
	{
		public void Init(QuadEdgeTriangle tri)
		{
			this._triQueue.AddLast(tri);
		}

		public void Init(IEnumerable<QuadEdgeTriangle> tris)
		{
			foreach (QuadEdgeTriangle value in tris)
			{
				this._triQueue.AddLast(value);
			}
		}

		public void VisitAll(ITraversalVisitor visitor)
		{
			while (this._triQueue.Count > 0)
			{
				QuadEdgeTriangle value = this._triQueue.First.Value;
				this._triQueue.RemoveFirst();
				this.Process(value, visitor);
			}
		}

		private void Process(QuadEdgeTriangle currTri, ITraversalVisitor visitor)
		{
			currTri.GetNeighbours();
			for (int i = 0; i < 3; i++)
			{
				QuadEdgeTriangle quadEdgeTriangle = (QuadEdgeTriangle)currTri.GetEdge(i).Sym.Data;
				if (quadEdgeTriangle != null && visitor.Visit(currTri, i, quadEdgeTriangle))
				{
					this._triQueue.AddLast(quadEdgeTriangle);
				}
			}
		}

		private readonly LinkedList<QuadEdgeTriangle> _triQueue = new LinkedList<QuadEdgeTriangle>();
	}
}
